# -*- coding: UTF-8 -*-

import curses

def dumbmenu(title,items):
    '''Menu test with curses
    dumbmenu([]) -> int
    '''
    stdscr = curses.initscr() #kui kasutada samast sessioonist koguaeg ,siis võib aint korra initida
    stdscr.erase()
    curses.start_color()
    curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
    curses.noecho()
    stdscr.keypad(1)

    begin_x = 0 ; begin_y = 0
    height = 20 ; width = 80
    cur_x = 0; cur_y = 0
    #win = curses.newwin(height, width, begin_y, begin_x)
    #win.border('|', '|', '-', '-', '+', '+', '+', '+')
    #win.keypad(1)

    stdscr.addstr(begin_y,begin_x,"%s (q to exit):"%title,curses.color_pair(1) | curses.A_BLINK )
    
    y = 0
    for i in items:
        if len(i) > width: i = i[0:len(i)-3] + "..."
        stdscr.addstr(begin_y + y + 1,begin_x + 3 + cur_x,i,curses.A_BLINK )
        y += 1

    stdscr.refresh()
    curses.curs_set(0)
    
    def quit():
        #Terminate
        curses.curs_set(1)
        #curses.nocbreak(); 
        stdscr.keypad(0); curses.echo()
        curses.endwin()
        
    while 1:
        stdscr.addstr(begin_y + 1 + cur_y,begin_x + cur_x,"*>",curses.color_pair(0))
        c = stdscr.getch()
        stdscr.addstr(begin_y + 1 + cur_y,begin_x + cur_x,"  ",curses.color_pair(0))
        stdscr.refresh()
        
        if c == curses.KEY_UP:
            cur_y -= 1
            if cur_y<0: cur_y = len(items)-1
        elif c == curses.KEY_DOWN:
            cur_y += 1
            if cur_y >= len(items): cur_y = 0
        elif c == curses.KEY_HOME: cur_x = cur_y = 0
        elif c == 10: break
            #stdscr.addstr(7 + len(items),0,"Selected:%s"%items[cur_y],curses.color_pair(0))
        elif c == ord('q'): 
            quit()
            return -1
        
        if __name__=="__main__" and c == ord('q'): break  # Exit the while()
        

    quit()
    return cur_y

if __name__ == "__main__":
    print "Got",dumbmenu("Stupid menu",['a','b','c','d'*90])
